/**
 * ProtoActor-Go WASM 集成演示
 * 
 * 此示例展示如何在 TypeScript 中使用通过 WASM 编译的 ProtoActor-Go 框架
 */

import { WasmBridgeFactory } from '../wasm/wasmBridge';
import { WasmEventType } from '../wasm/wasmEvents';
import { ActorBridge, ActorMessage, ActorPID, ActorEventType } from '../wasm/actorBridge';

/**
 * 运行 ProtoActor-Go WASM 示例
 */
export async function runProtoActorGoWasmExample() {
  console.log('===== ProtoActor-Go WASM 示例 =====');
  
  try {
    // 创建并初始化 ActorBridge
    const actorBridge = new ActorBridge();
    
    // 注册事件监听器
    setupEventListeners(actorBridge);
    
    // 初始化 WASM 模块
    await actorBridge.initialize('./protoactor.wasm');
    console.log('ActorBridge 初始化成功');
    
    // 注册自定义消息处理器
    actorBridge.registerMessageHandler('handleGreeting', (message: ActorMessage) => {
      console.log(`收到问候消息: ${JSON.stringify(message)}`);
      return { response: `你好，${message.type}！` };
    });
    
    // 获取版本信息
    const version = await actorBridge.getVersion();
    console.log(`ProtoActor-Go WASM 版本: ${version}`);
    
    // 创建 Actor
    const actorPid = await actorBridge.createActor('greetingActor');
    console.log(`Actor 已创建: ${JSON.stringify(actorPid)}`);
    
    // 发送消息到 Actor
    const greeting: ActorMessage = { 
      type: 'Greeting', 
      content: 'Hello from TypeScript!'
    };
    
    const response = await actorBridge.sendMessage(actorPid, greeting);
    console.log(`收到响应: ${JSON.stringify(response)}`);
    
    // 等待一段时间以便观察事件
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 停止 Actor
    const stopResult = await actorBridge.stopActor(actorPid);
    console.log(`Actor 停止结果: ${JSON.stringify(stopResult)}`);
    
    console.log('===== ProtoActor-Go WASM 示例完成 =====');
  } catch (error) {
    console.error('WASM 示例运行失败:', error);
  }
}

/**
 * 设置事件监听器
 * @param actorBridge ActorBridge 实例
 */
function setupEventListeners(actorBridge: ActorBridge) {
  // Actor 创建事件
  actorBridge.addEventListener(ActorEventType.CREATED, (data) => {
    console.log(`[事件] Actor 已创建: ${JSON.stringify(data)}`);
  });
  
  // Actor 停止事件
  actorBridge.addEventListener(ActorEventType.STOPPED, (data) => {
    console.log(`[事件] Actor 已停止: ${JSON.stringify(data)}`);
  });
  
  // 消息发送事件
  actorBridge.addEventListener(ActorEventType.MESSAGE_SENT, (data) => {
    console.log(`[事件] 消息已发送: ${JSON.stringify(data.message)}`);
  });
  
  // 消息接收事件
  actorBridge.addEventListener(ActorEventType.MESSAGE_RECEIVED, (data) => {
    console.log(`[事件] 消息已接收: ${JSON.stringify(data)}`);
  });
  
  // 错误事件
  actorBridge.addEventListener(ActorEventType.ERROR, (data) => {
    console.error(`[事件] 错误: ${JSON.stringify(data)}`);
  });
}

// 导出兼容旧名称的函数
export const runWasmExample = runProtoActorGoWasmExample;

// 如果是直接运行此文件，则执行示例
if (typeof window !== 'undefined' || (typeof Bun !== 'undefined')) {
  // 检查是否作为主模块运行（基于 URL 或脚本名称）
  const isMainModule = (typeof document !== 'undefined' && 
                        document.currentScript && 
                        (document.currentScript as HTMLScriptElement).src.includes('wasm-demo')) ||
                       (typeof Bun !== 'undefined' && Bun.main?.includes('wasm-demo'));
  
  if (isMainModule) {
    runProtoActorGoWasmExample().catch(err => console.error('WASM 示例运行失败:', err));
  }
} 